package handlers

import (
	"encoding/json"
	"logi-perm/cache"
	"logi-perm/models"
	"logi-perm/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	redis_key := "login_" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	token := pkg.TokenHandler(int(user.ID))
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
		"jwt":  token,
	})
	return
}
func CreateUserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	rid, _ := strconv.Atoi(c.Query("rid"))
	if rid == 0 || uid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "关联成功",
		"data": data,
	})
	return
}
func CreateRoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: nid,
		Nid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "关联成功",
		"data": data,
	})
	return
}
func DetailUserRole(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.uid
	*/
	uid := c.Query("uid")
	var role models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.uid").
		Where("user_roles.uid=?", uid).Debug().First(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}
func DetailRoleNode(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.rid
	*/
	rid := c.Query("rid")
	var node models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.rid").
		Where("role_nodes.rid=?", rid).Debug().First(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
	return
}
func ListUser(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "50"))
	offset := (page - 1) * size
	var user []models.User
	redis_key := "list_user_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&user)
		jsonData, _ := json.Marshal(&user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	var total int64
	models.DB.Model(&user).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  user,
		"total": total,
	})
	return
}
func DetailUser(c *gin.Context) {
	id := c.Query("id")
	var user models.User
	redis_key := "detail_user_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Debug().Find(&user)
		jsonData, _ := json.Marshal(&user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return
}
